package cn.yunyichina.provider.reservation.service.impl;

import cn.yunyichina.provider.framework.exception.CallException;
import cn.yunyichina.provider.framework.page.PageInfo;
import cn.yunyichina.provider.reservation.dao.ItemRuleDao;
import cn.yunyichina.provider.reservation.entity.ItemRule;
import cn.yunyichina.provider.reservation.service.ItemRuleService;
import cn.yunyichina.utils.convert.JsonUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 项目规则
 */
@Service("itemruleServiceImpl")
public class ItemRuleServiceImpl implements ItemRuleService {

    @Resource
    private ItemRuleDao itemRuleDao;

    public List<ItemRule> listItemRule(String strJson) {
        JSONObject jsonObj = JsonUtils.parseObject(strJson);
        ItemRule itemRule = JsonUtils.parseObject(strJson, ItemRule.class);

        PageInfo pageInfo = null;
        if (jsonObj.containsKey("pageInfo")) {
            pageInfo = jsonObj.getObject("pageInfo", PageInfo.class);
        } else {
            pageInfo = new PageInfo();
        }
        List<String> orderColumns = null;
        if (jsonObj.containsKey("orderColumns")) {
            orderColumns = new ArrayList<String>();
            String str = jsonObj.getString("orderColumns");
            String[] listObj = str.split(",");
            for (Object field : listObj) {
                orderColumns.add((String) field);
            }
        }

        List<String> selects = null;
        if (jsonObj.containsKey("selects")) {
            selects = new ArrayList<String>();
            String str = jsonObj.getString("selects");
            String[] listObj = str.split(",");
            for (Object field : listObj) {
                selects.add((String) field);
            }
        }

        boolean isAsc = true;
        if (jsonObj.containsKey("isAsc")) {
            isAsc = jsonObj.getBooleanValue("isAsc");
        }

        List<ItemRule> list = itemRuleDao.select(itemRule, selects, orderColumns, isAsc, pageInfo);
        return list;
    }

    public Map<String, Object> getItemRuleByItemId(String strJson) {
        JSONObject jsonObj = JsonUtils.parseObject(strJson);

        //项目规则表的字段id值=item_id值
        jsonObj.put("id", jsonObj.getString("item_id"));
        return getItemRule(JsonUtils.toJsonString(jsonObj));
    }

    /**
     * @param strJson id
     * @return 额外信息：schedule_start_date开始显示的起始日期（YYYY-MM-DD),schedule_enables从开始显示的日期开始算起，标识上午/下午能否选择的二维字符串数组格式[["Y","N"],["Y","Y"],....]
     */
    public Map<String, Object> getItemRule(String strJson) {
        JSONObject jsonObj = JsonUtils.parseObject(strJson);
        ItemRule entity = itemRuleDao.selectById(jsonObj.getString("id"));

        JSONObject jsonItemRuleObj = JsonUtils.parseObject(entity);

        if (entity != null) {
            String scheduleInfo = entity.getScheduleInfo();
            if (StringUtils.isNotEmpty(scheduleInfo)) {

                int showDay = entity.getShowDay();

                //解析出每星期几的定义
                String[] dayInfos = scheduleInfo.split(";");
                Map<String, String[]> mapWeek = new LinkedHashMap<>();
                for (String info : dayInfos) {
                    String[] items = info.split(",");
                    String week = items[0].trim();
                    String[] enables = new String[]{"N", "N"};
                    if (items[1].equals("1") && items[2].length() > 0 && Integer.parseInt(items[2]) > 0) {
                        enables[0] = "Y";
                    } else if (items[1].equals("2") && items[2].length() > 0 && Integer.parseInt(items[2]) > 0) {
                        enables[1] = "Y";
                    }

                    //长度5位
                    if (items.length > 3) {
                        if (items[3].equals("1") && items[4].length() > 0 && Integer.parseInt(items[4]) > 0) {
                            enables[0] = "Y";
                        } else if (items[3].equals("2") && items[4].length() > 0 && Integer.parseInt(items[4]) > 0) {
                            enables[1] = "Y";
                        }
                    }
                    mapWeek.put(week, enables);

                }

                //确定开始选择日期
                String[][] schInfos = new String[showDay][];
                Calendar c = Calendar.getInstance();
                /*
                 * 20161010 修改为周六日不跳过
                int curWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
                if (curWeek == 0) {
                    curWeek = 7;
                }
                //周六日时，开始时间跳到下周一
                if (curWeek >= 6) {
                    c.add(Calendar.DATE, 8 - curWeek);
                }
                */
                DateFormat YYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
                jsonItemRuleObj.put("schedule_start_date", YYYYMMDD.format(c.getTime()));
                for (int i = 0; i < showDay; i++) {
                    int curWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
                    if (curWeek == 0) {
                        curWeek = 7;
                    }

                    //星期几匹配成功
                    if (mapWeek.containsKey(curWeek + "")) {
                        schInfos[i] = mapWeek.get(curWeek + "");
                    } else {
                        schInfos[i] = new String[]{"N", "N"};
                    }
                    c.add(Calendar.DATE, 1);
                }
                jsonItemRuleObj.put("schedule_enables", schInfos);
            }
        } else {
            return null;
        }

        return jsonItemRuleObj;
    }

    public ItemRule addItemRule(String strJson) {

        ItemRule itemRule = JsonUtils.parseObject(strJson, ItemRule.class);

        ItemRule existRule = itemRuleDao.selectByItemId(itemRule.getItemId());
        if (existRule != null) {
            throw new CallException("6900", "该项目已经存在规则");
        }

//    	itemRule.setId(java.util.UUID.randomUUID().toString().replaceAll("-", ""));
        itemRule.setId(itemRule.getItemId());
        itemRuleDao.insert(itemRule);

        itemRule = itemRuleDao.selectById(itemRule.getId());
        return itemRule;
    }

    public void updateItemRule(String strJson) {
        ItemRule itemRule = JsonUtils.parseObject(strJson, ItemRule.class);
        itemRuleDao.update(itemRule);
    }

}
